package com.walk.zworld.ui.activity.my

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.ViewModelProvider
import com.walk.zworld.R
import com.walk.zworld.mvvm.viewModel.CommonViewModel
import com.walk.zworld.mvvm.vm.MyCollectActivityViewModel
import com.walk.zworld.ui.adapter.CollectAdapter
import com.walk.zworld.webView.WebViewActivity
import com.walk.zworld.webView.isInvalidClick
import com.base.lib.base.view.BaseMvvmListActivity
import com.base.lib.httpUtils.CollectionArticle


class MyCollectActivity : BaseMvvmListActivity<CollectionArticle, MyCollectActivityViewModel, CollectAdapter>() {

    override fun onBindAdapter(): Class<CollectAdapter> = CollectAdapter::class.java

    override fun onBindViewModel(): Class<MyCollectActivityViewModel> = MyCollectActivityViewModel::class.java
    private val commonVM: CommonViewModel by lazy { ViewModelProvider(this).get(CommonViewModel::class.java) }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initData() {
        setTop("我的收藏")
        onRefreshEvent()
    }

    override fun initView() {
        mAdapter.run {
            setOnItemClickListener { adapter, view, position ->
                if (data.size != 0) {
                    val data = data[position]
                    WebViewActivity.start(this@MyCollectActivity, data.id, data.title, data.link)
                }
            }
            addChildClickViewIds(R.id.iv_like)
            setOnItemChildClickListener { adapter, view, position ->
                if (isInvalidClick(view)) return@setOnItemChildClickListener
                if (data.size == 0) return@setOnItemChildClickListener
                when (view.id) {
                    R.id.iv_like -> {
                        removeCollectArticle(data[position].id, data[position].originId)
                        mAdapter.removeAt(position)
                    }
                }
            }
        }
    }

    private fun removeCollectArticle(id: Int, originId: Int) {
        showInitLoadView()
        commonVM.removeCollectArticle(id, originId)
            .observe(this@MyCollectActivity, {
                hideInitLoadView()
            })
    }

}